<?php
/**
 * @package     Helpers.php
 * @author      Jing Tang <tangjing3321@gmail.com>
 * @link        http://www.slimphp.net/
 * @version     2.0
 * @copyright   Copyright (c) http://www.slimphp.net
 * @date        2017年7月24日
 */

if (! function_exists('download')) {
    /**
     * File download
     * 
     * @param string $url
     * @param string $dir
     * @return boolean
     */
    function download($url, $dir)
    {
        try {
            if (! filter_var($url, FILTER_VALIDATE_URL)) {
                return false;
            }
            $dir = rtrim($dir, '/');
            $uri = parse_url($url);
            $path = explode('/', $uri['path']);
            unset($path[count($path) - 1]);
            $path = implode('/', $path);
            filesystem()->makeDirectory($dir . $path, 0777, true, true);
            $newfname = $dir . $uri['path'];
            if (! is_file($newfname) || ! filesize($newfname)) {
                if ($file = fopen($url, "rb")) {
                    if ($newf = fopen($newfname, "wb")) {
                        while (! feof($file)) {
                            fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
                        }
                        fclose($file);
                        fclose($newf);
                        return true;
                    }
                    else {
                        ! $file ?: fclose($file);
                        ! $newf ?: fclose($newf);
                    }
                }
                else {
                    ! $file ?: fclose($file);
                    return false;
                }
            }
            else {
                return true;
            }
        }
        catch (\Exception $e) {
            return false;    
        }
    }
}